/*
 *  Copyright 2012 Dirk Vranckaert
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package eu.vranckaert.vvl.service.impl;

import android.content.Context;
import android.util.Log;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndCategory;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndContent;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndEntry;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndFeed;
import com.google.code.rome.android.repackaged.com.sun.syndication.fetcher.FeedFetcher;
import com.google.code.rome.android.repackaged.com.sun.syndication.fetcher.FetcherException;
import com.google.code.rome.android.repackaged.com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import com.google.code.rome.android.repackaged.com.sun.syndication.io.FeedException;
import eu.vranckaert.vvl.exception.ServiceException;
import eu.vranckaert.vvl.exception.webservice.InformationTextServiceException;
import eu.vranckaert.vvl.exception.webservice.WebServiceRequestFailureException;
import eu.vranckaert.vvl.model.TrafficInfoTextEnum;
import eu.vranckaert.vvl.model.TrafficInfoText;
import eu.vranckaert.vvl.service.InformationTextService;
import eu.vranckaert.vvl.utils.context.Logger;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * User: DIRK VRANCKAERT
 * Date: 17/02/12
 * Time: 11:21
 */
public class InformationTextServiceImpl extends WebServiceImpl implements InformationTextService {
    private static final String LOG_TAG = InformationTextServiceImpl.class.getSimpleName();
    private static final String RSS_FEED_PARAMS_SEPARATOR = "|";
    
    public InformationTextServiceImpl(Context ctx) {
        super(ctx);
    }

    @Override
    public List<TrafficInfoText> findByCriteria(
            List<TrafficInfoTextEnum.InformationType> selectedInformationTypes,
            List<TrafficInfoTextEnum.Region> selectedRegions,
            List<TrafficInfoTextEnum.Highroad> selectedHighroads,
            List<TrafficInfoTextEnum.SecondaryRoads> selectedSecondaryRoads) throws ServiceException, InformationTextServiceException {
        StringBuilder types = new StringBuilder();
        for (TrafficInfoTextEnum.InformationType infoType : selectedInformationTypes) {
            types.append(infoType.getValue());
            types.append(RSS_FEED_PARAMS_SEPARATOR);
        }
        if (types.charAt(types.length()-1) == RSS_FEED_PARAMS_SEPARATOR.charAt(0)) {
            types.deleteCharAt(types.length()-1);
        }

        StringBuilder data = new StringBuilder();
        for (TrafficInfoTextEnum.Region region : selectedRegions) {
            data.append(region.getValue());
            data.append(RSS_FEED_PARAMS_SEPARATOR);
        }
        for (TrafficInfoTextEnum.Highroad highroad : selectedHighroads) {
            data.append(highroad.getValue());
            data.append(RSS_FEED_PARAMS_SEPARATOR);
        }
        for (TrafficInfoTextEnum.SecondaryRoads secondaryRoad : selectedSecondaryRoads) {
            data.append(secondaryRoad.getValue());
            data.append(RSS_FEED_PARAMS_SEPARATOR);
        }
        if (data.charAt(data.length()-1) == RSS_FEED_PARAMS_SEPARATOR.charAt(0)) {
            data.deleteCharAt(data.length()-1);
        }

        String url = String.format(TrafficInfoTextEnum.TEXT_IMAGE_URL, data.toString(), types.toString());
        SyndFeed feed = null;

        try {
            FeedFetcher feedFetcher = new HttpURLFeedFetcher();
            feed = feedFetcher.retrieveFeed( new URL( url ) );
        } catch (FetcherException e) {
            throw new WebServiceRequestFailureException("Cannot get the text data", e, e.getResponseCode());
        } catch (FeedException e) {
            throw new InformationTextServiceException("Cannot parse the data", e);
        } catch (IOException e) {
            throw new ServiceException("A problem occured while getting the text data", e);
        }

        List<SyndEntry> entries = feed.getEntries();

        List<TrafficInfoText> resultList = new ArrayList<TrafficInfoText>();
        for (SyndEntry entry : entries) {
            SyndCategory syndCategory = (SyndCategory) entry.getCategories().get(0);
            TrafficInfoTextEnum.InformationType cat = TrafficInfoTextEnum.InformationType.getByRssValue(syndCategory.getName());
            TrafficInfoText tit = new TrafficInfoText(cat, entry.getTitle(), entry.getPublishedDate());
            try {
                tit.setLink(new URI(entry.getLink()));
            } catch (URISyntaxException e) {
                if (Logger.isLogEnabled())
                    Log.d(LOG_TAG, "The link " + entry.getLink() + " cannot be parsed to a URI");
            }
            SyndContent description = entry.getDescription();
            tit.setDescription(description.getValue());
            
            resultList.add(tit);
        }

        return resultList;
    }
}
